package com.tanhua.dubbo.api.mongo;

import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Voice;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author LiuKeLin
 * @title: VoiceApiImpl
 * @projectName tanhua-practice
 * @description: TODO
 * @date 2022/2/2110:44
 */
@DubboService
@Slf4j
public class VoicesApiImpl implements VoicesApi {

    @Autowired
    private MongoTemplate mongoTemplate;


    //添加语音
    @Override
    public void addVoice(Voice voice) {
        voice.setCreated(System.currentTimeMillis());
        mongoTemplate.insert(voice);
    }

    /***
     * 排除异性 本人
     * @param userInfo
     * @return
     */
    @Override
    public List<Voice> findVoices(UserInfo userInfo) {
        Query query = new Query();
        //如果是男性则查询女性 不是女生则查询男性
        String gender = StringUtils.equals(userInfo.getGender(), "man") ? "woman" : "man";
        // 排除性别、自己   根据性别查询 并且不查询自己
        query.addCriteria(Criteria.where("gender").is(gender).and("userId").ne(userInfo.getId()));
        //查询到的是异性 分本人 数据
        return mongoTemplate.find(query, Voice.class);
    }

    /**
     * 好友表中查询是否为好友
     *
     * @param userId
     * @param id
     * @return
     */
    @Override
    public boolean isFreed(Long userId, Long id) {
        Query query = new Query();
        //好友表中查询是否为好友
        query.addCriteria(Criteria.where("userId").is(userId).and("friendId").is(id));
        Friend one = mongoTemplate.findOne(query, Friend.class);
        return !ObjectUtils.isEmpty(one);
    }
}

